/*
package com.example.demo.filter;

import com.alibaba.fastjson.JSONObject;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.WriteListener;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.security.SecureRandom;

@Slf4j
@Component
public class LogFilter implements Filter {
	
	private static final char[] SEEDS = "QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm1234567890".toCharArray();
	
	private final static String REQUEST_ID = "requestId";
	
	@Override
    public void init(FilterConfig filterConfig) throws ServletException {
		log.info("--------------logFilter init 过滤器初始化------------");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
    	//log.info("--------------logFilter doFilter 过滤器初始化开始过滤------------");
    	long start=System.currentTimeMillis();
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;

        String uri=httpServletRequest.getRequestURI();
        ServletRequest requestWrapper = new BodyReaderHttpServletRequestWrapper(httpServletRequest);
        
        ResponseWrapper responseWrapper = new ResponseWrapper(httpServletResponse); // 包装响应对象 resp 并缓存响应数据
        String body = HttpHelper.getBodyString(requestWrapper);
        log.info("receive request {} param {}" ,uri,body);
        JSONObject requestJso = null;
        try {
            requestJso = JSONObject.parseObject(body);
        } catch (Exception e) {
            log.warn("body transfer Json failed:{}", body);
        }
        
        if(requestJso != null) {
        	String requestId = requestJso.getString(REQUEST_ID);
            if (StringUtils.isEmpty(requestId)) {
                StringBuffer buffer = new StringBuffer();
                SecureRandom random = new SecureRandom();
                for(int i=0; i< 16; i++){
                    buffer.append(SEEDS[random.nextInt(SEEDS.length)]);
                }
                requestId = buffer.toString();
            }

            log.info("do filter chain currentLoginUser");
            StringBuffer sb = new StringBuffer("<U=");
            String currentLoginUser = requestJso.getString("currentLoginUser");
            if(StringUtils.isNotBlank(currentLoginUser)) {
            	JSONObject loginUserObj = JSONObject.parseObject(currentLoginUser);
            	sb.append(loginUserObj != null ? loginUserObj.getString("userId") : "");
            }
            sb.append(",C=");
            sb.append(requestJso.getString("caseId"));
            sb.append(",R=");
            sb.append(requestId);
            sb.append(">");
            MDC.put(REQUEST_ID, sb.toString());
        } else {
        	log.info("receive request {} requestJso is null.",uri);
        }
        log.info("do filter chain");

        // 防止流读取一次后就没有了, 所以需要将流继续写出去
        filterChain.doFilter(requestWrapper, responseWrapper);       
        byte[] responseByteArray = responseWrapper.getBytes();
        if(uri != null && uri.contains(".do")) {
            String  resultData=  new String(responseByteArray, "utf-8");
            log.info("response {} responseJson:{}", uri, resultData);
        }
        ServletOutputStream servletOutputStream = httpServletResponse.getOutputStream();
        servletOutputStream.write(responseByteArray);
        long end=System.currentTimeMillis();
        log.info("response {} cost {} ms",uri,(end-start));
        MDC.remove(REQUEST_ID);
    }
    
    

	@Override
    public void destroy() {
    	MDC.remove(REQUEST_ID);
    	log.info("--------------logFilter destroy 过滤器销毁------------");
    }
}


class ResponseWrapper extends HttpServletResponseWrapper {
    private ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    private HttpServletResponse response;
    private PrintWriter pwrite;

    public ResponseWrapper(HttpServletResponse response) {
        super(response);
        this.response = response;
    }

    @Override
    public ServletOutputStream getOutputStream() throws IOException {
        return new MyServletOutputStream(bytes); // 将数据写到 byte 中
    }

    */
/**
     * 重写父类的 getWriter() 方法，将响应数据缓存在 PrintWriter 中
     *//*

    @Override
    public PrintWriter getWriter() throws IOException {
        try{
            pwrite = new PrintWriter(new OutputStreamWriter(bytes, "utf-8"));
        } catch(UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return pwrite;
    }

    */
/**
     * 获取缓存在 PrintWriter 中的响应数据
     * @return
     *//*

    public byte[] getBytes() {
        if(null != pwrite) {
            pwrite.close();
            return bytes.toByteArray();
        }

        if(null != bytes) {
            try {
                bytes.flush();
            } catch(IOException e) {
                e.printStackTrace();
            }
        }
        return bytes.toByteArray();
    }

    class MyServletOutputStream extends ServletOutputStream {
        private ByteArrayOutputStream ostream ;

        public MyServletOutputStream(ByteArrayOutputStream ostream) {
            this.ostream = ostream;
        }

        @Override
        public void write(int b) throws IOException {
            ostream.write(b); // 将数据写到 stream　中
        }

		@Override
		public boolean isReady() {
			// TODO Auto-generated method stub
			return false;
		}

		@Override
		public void setWriteListener(WriteListener writeListener) {
            //This is an empty method but necessary
		}
    }

}
*/
